package com.jsite.modules.aop;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Order(-1)
public class DataSourceAop {

//    @Pointcut("@annotation(com.jsite.modules.aop.annotation.Slave) " +
//            "&& (execution(* com.jsite.modules.*.service..*.find*(..)) " +
//            "|| execution(* com.jsite.modules.*.service..*.get*(..)))" +
//            "|| execution(* com.jsite.common.service.*.find*(..))" +
//            "|| execution(* com.jsite.common.service.*.get*(..))" )
//    public void readPointcut() {
//    }

//    @Pointcut("@annotation(com.jsite.modules.aop.annotation.Master) " +
//            "|| execution(* com.jsite.modules.*.service..*.save*(..)) " +
//            "|| execution(* com.jsite.modules.*.service..*.delete*(..)) " +
//            "|| execution(* com.jsite.common.service.*.save*(..))" +
//            "|| execution(* com.jsite.common.service.*.delete*(..))" )
//    public void writePointcut() {
//    }

    @Pointcut("@annotation(com.jsite.modules.aop.annotation.Slave)")
    public void readPointcut() {
    }

    @Pointcut("@annotation(com.jsite.modules.aop.annotation.Master)")
    public void writePointcut() {
    }

    @Before("readPointcut()")
    public void read() {
        DBContextHolder.slave();
    }

    @Before("writePointcut()")
    public void write() {
        DBContextHolder.master();
    }


    /**
     * 另一种写法：if...else...  判断哪些需要读从数据库，其余的走主数据库
     */
//    @Before("execution(* com.cjs.example.service.impl.*.*(..))")
//    public void before(JoinPoint jp) {
//        String methodName = jp.getSignature().getName();
//
//        if (StringUtils.startsWithAny(methodName, "get", "select", "find")) {
//            DBContextHolder.slave();
//        }else {
//            DBContextHolder.master();
//        }
//    }
}
